package com.axino.accessPlatform.web;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 商户token获取
 *
 * @author gbzdyf@126.com
 * @create 2018-04-23 15:38
 **/
@WebServlet("/token")
public class Oauth2AccessToken extends HttpServlet {

    String _url = "https://opentest.jss.com.cn/accessToken"; //获取token地址
    String _header = "application/x-www-form-urlencoded";
    String client_id = "yb1OQpps";  //创建应用后，分配给应用的appKey
    String client_secret = "7A4796A291CE43B1"; //创建应用后，分配给应用的appSecret
    String token_grant_type = "authorization_code";   //授权类型，在本步骤中，此值为“authorization_code”
    String redirect_uri = "http://172.30.5.96:8080/";   //回调地址，必传且不能为空

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        PrintWriter out = resp.getWriter();


        String code = String.valueOf(req.getParameterMap().get("code")[0]); //临时授权码code
        String taxNum = String.valueOf(req.getParameterMap().get("taxnum")[0]); //授权企业的税号，获取临时授权码返回的taxnum
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpUriRequest build = RequestBuilder
                    .post(_url)
                    .addHeader("Content-Type",_header)
                    .addParameter("client_id", client_id)
                    .addParameter("client_secret", client_secret)
                    .addParameter("grant_type", token_grant_type)
                    .addParameter("redirect_uri", redirect_uri)
                    .addParameter("code", code)
                    .addParameter("taxNum", taxNum)
                    .build();

            //请求
            CloseableHttpResponse response = client.execute(build);
            HttpEntity entity = response.getEntity();

            String resValue = "";
            if (entity != null) {
                resValue = EntityUtils.toString(entity);
                System.out.println("response: " + resValue);
            }

            //释放资源
            EntityUtils.consume(entity);

            //定时刷新授权
            if (!StringUtils.isEmpty(resValue)) {
                Map<String, Object> map = parseJSON2Map(resValue);
                new RefreshTokenTimer(60, 29 * 24 * 60, _url, _header,
                        String.valueOf(map.get("refresh_token")), client_secret, String.valueOf(map.get("userId"))).executeTimer();
                out.write(resValue);
            } else {
                out.write("获取授权报错");
            }
        } catch (Exception e) {
            out.write(e.getMessage());
        } finally {
            out.close();
        }
    }

    public static Map<String, Object> parseJSON2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        //最外层解析
        JSONObject json = JSONObject.fromObject(jsonStr);
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            //如果内层还是数组的话，继续解析
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator<JSONObject> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
